package com.niubility.controller;


import com.niubility.entity.*;
import com.niubility.exception.CustomException;
import com.niubility.server.*;
import com.niubility.server.Impl.*;
import com.niubility.vo.LoadAll;


import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@RestController
public class CheckDepController {
    private Logger logger = Logger.getLogger(CheckDepController.class);
    //检查表的业务层对象
    @Resource
    private ICheckDepServer checkDepServer;
    //正式社团表的业务层对象
    @Resource
    private IDepartmentService departmentService;
    //检索表的业务层对象
    @Resource
    private SearchServer searchServer;
    //大学业务层对象
    @Resource
    private IColService collegeService;
    //密码表业务层对象
    @Resource
    private IPwdService pwdService;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    @Resource
    private IMessageServer messageServer;
    @RequestMapping("/CheckDepPass")
    public void ChcekOver(HttpServletResponse response, HttpServletRequest request) throws CustomException {
//        //System.out.println("通过表接收到数据");
        String depName = request.getParameter("depName");
        int depCollege = Integer.parseInt(request.getParameter("depCollege"));
        String callback = request.getParameter("callback");
        //System.out.println(depName+" "+depCollege+" "+callback);
        Department department = this.checkDepServer.select(depCollege,depName);
        int id = checkDepServer.LastInsertID();
        String result = null;
        SearchMain searchMain = null;
        Pwd pwd = new Pwd();
        pwd.setUserPwd(department.getDepPwd());

        //消息接口
        String massage = "#"+id+"#"+"您的社团"+depName+"已通过审核！";//拼接的消息字符串
        String text = depName+" "+department.getDepSign();
        int depMasterID = department.getDepMaster();
        ////System.out.println(massage);
        //待测试
        Message message = new Message();
        message.setMesText(massage);
        message.setMesMainid(depMasterID);
        message.setMesSendid(00000000);
        message.setMesText(massage);
        message.setMesDate(dateFormat.format(new Date()));

        try {
            boolean boolSave = departmentService.addDep(department);//向社团表添加社团
            boolean boolDelete = checkDepServer.Delete(depCollege, depName);//删除社团检查表中的社团
            boolean boolMassege = messageServer.InsertMessage(message)>0?true:false;
            result = callback + "(" + "{\"returncade\":" + "100}" + ")";
           ////System.out.println(boolDelete+" "+boolSave+" "+boolMassege);
            if(!(boolDelete&boolSave&boolMassege)){
                result = callback + "(" + "{\"returncade\":" + "108}" + ")";
                throw new CustomException();
            }else {
                id = departmentService.lastInsertId(depCollege, depName);
                pwd.setUserId(id);
                //1000001处获取数据库分配的ID
                searchMain = new SearchMain(id, depName, text);
                collegeService.updateColDeps(depCollege,1);//向大学添加社团
                //向查询表添加查询信息
                ////System.out.println("前期业务成功");
                searchServer.InsertInto(searchMain);
                pwdService.DepRig(pwd,Integer.toString(id));
            }
        }catch (Exception e) {
            result = callback + "(" + "{\"returncade\":" + "108}" + ")";
            try{
                response.getWriter().write(result);
            }catch (Exception s){
                result = callback + "(" + "{\"returncade\":" + "108}" + ")";
            }
            throw new CustomException();
        }
        try{
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("数传输失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description:查询分页信息
    * @Date: John 2018/1/27
    * @Params: 传入分页对象
    * @Return:然后所有所需页面的信息
    * 测试通过
    */
    @RequestMapping("/CheckDepLoadAll")
    public void LoadAll(HttpServletResponse response, HttpServletRequest request) throws CustomException {
        response.setCharacterEncoding("utf-8");
       // //System.out.println("申请已接收");
        String callback = request.getParameter("callback");
        int num = Integer.parseInt(request.getParameter("num"));
        int nowPage = Integer.parseInt(request.getParameter("nowPage"));
       // //System.out.println(callback+" "+" "+num+" "+nowPage);
        String result = null;
        try{
            int pageLagerNum = checkDepServer.PageNum(num);//最大的页码数
           // //System.out.println(pageLagerNum);
            List<Department> list = checkDepServer.LoadAll(num*(nowPage-1),num);//按格式取10条元组
           // //System.out.println(list.toString());
            LoadAll loadAll = new LoadAll();
            loadAll.setList(list);
            loadAll.setPageMore(pageLagerNum);
            result = callback+"("+JSONArray.fromObject(loadAll).toString()+")";
            //result = "<script type=\"javascript/text\">window.onload=funcation(){alert('jfghfhg');}</script>";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                response.getWriter().write(result);
            }catch (Exception s){
                logger.debug("数据传输错误."+s);
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("数据传输错误."+e);
        }
    }
    /*
    * @Author:John
    * @Description:查询单条目录
    * @Date: John 2018/1/27
    * @Params: 传入查询对象
    * @Return:返回查询到的条目
    * 测试通过
    */
    @RequestMapping("/CheckDepSetect")
    public void Select(HttpServletResponse response, HttpServletRequest request) throws CustomException {
        response.setCharacterEncoding("utf-8");
        String CollegeName = request.getParameter("depCollege");
        String callback = request.getParameter("callback");
        String depName = request.getParameter("depName");
        String result = null;
        try {
            College college = collegeService.loadByColName(CollegeName);
            //查询大学ID
            Department department = checkDepServer.select(college.getColId(),depName);
            //System.out.println(department);
            result = callback+"("+JSONArray.fromObject(department).toString()+")";

        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                response.getWriter().write(result);
            }catch (Exception s){
                logger.debug("数据传输错误."+s);
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("数据传送失败."+e);
        }
    }

    /*
    * @Author:John
    * @Description:传入操作对象，提取信息进行删除
    * @Date: John 2018/1/27
    * @Params: 传入vod对象
    * @Return:返回boolean 值，判断是否删除成功
    * 测试通过
    */
    @RequestMapping("/CheckDepDelete")
    public void Delete(HttpServletResponse response, HttpServletRequest request) throws CustomException {
        String callback = request.getParameter("callback");
        String name = request.getParameter("depName");
        int depCollege = Integer.parseInt(request.getParameter("depCollege"));

        Message message = new Message();
        message.setMesSendid(000000000);
        message.setMesMainid(this.checkDepServer.select(depCollege,name).getDepMaster());
        message.setMesDate(dateFormat.format(new Date()));
        message.setMesText("您的社团"+name+"未通过审核！！");
        String result = null;
        //System.out.println(name+" "+depCollege);
        try {
            boolean bool = checkDepServer.Delete(depCollege, name);
            boolean bool2 = messageServer.InsertMessage(message)>0?true:false;
            //System.out.println(bool+" "+bool2);
            if(bool){
                result = callback + "("+"{\"returncade\":"+"100}"+")";
            }else {
                result = callback + "("+"{\"returncade\":"+"108}"+")";
            }
            //焦鑫预留消息接口，社团审核未通过
        } catch (Exception e) {
            result = callback + "("+"{\"returncade\":"+"108}"+")";
            try {
                response.getWriter().write(result);
            }catch (Exception s){
                logger.debug("数据传输错误."+s);
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("删除传输失败."+e);
        }
    }
    /*
    * @Author:John
    * @Description:增加操作，增加到检查表
    * @Date: John 2018/1/27
    * @Params: 传入增加的dep对象
    * @Return:返回一个是否增加成功
    * 测试通过
    */
    @RequestMapping("/CheckDepSave")
    public void Save(HttpServletResponse response, HttpServletRequest request) throws CustomException {
        response.setCharacterEncoding("utf-8");
        //System.out.println("数据输入！");
        String callback = request.getParameter("callback");
        String depName = request.getParameter("depName");
        String depAcount = request.getParameter("depAcount");
        int depMaster = Integer.parseInt(request.getParameter("depMaster"));
        //聚合修改
        //int depMaster = (Integer) request.getSession().getAttribute("userId");
        String depTel = request.getParameter("depTel");
        String depCollegeName = request.getParameter("depCollege");
        String depSign = request.getParameter("depSign");
        //String depPicture = request.getParameter("depPicture");
        String depPwd = request.getParameter("depPwd");
        int depCollege = 0;
        try{
            depCollege = collegeService.loadByColName(depCollegeName).getColId();
            //System.out.println("获取到大学id");
        }catch (Exception e){
            try {
                response.getWriter().write(callback+"("+"{\"returncade\":"+"108}"+")");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        String result = null;
        Department department = new Department();
        department.setDepAcount(depAcount);
        department.setDepPwd(depPwd);
        department.setDepMaster(depMaster);
        department.setDepName(depName);
        department.setDepTel(depTel);
        department.setDepCollege(depCollege);
        department.setDepSign(depSign);
        //department.setDepPicture(depPicture);
        department.setDepDate(dateFormat.format(new Date()));
        ////System.out.println(department.toString());
        try {
            if(checkDepServer.Save(department)){
                result = callback+"("+"{\"returncade\":"+"100}"+")";
                //System.out.println(result);
            }else {
                logger.debug("存储错误");
                result = callback + "(" + "{\"returncade\":" + "108}" + ")";
            }
        }catch (Exception e){
            logger.debug("传输错误"+e);
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try{
                response.getWriter().write(result);
            }catch (Exception s){
                logger.debug("数据传输失败."+s);
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("数据传输失败"+e);
        }
    }
}
